import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:sptapp/widget/common_widget.dart';

import '../../api/interface/login_api.dart';
import '../../api/request/response_data.dart';
import '../../basic/base_info.dart';
import '../../config/const.dart';
import '../../moudle/message.dart';
import '../../utils/regex_tool.dart';

class ForgetPwd extends StatefulWidget {
  final int type; //1 忘记密码  2修改密码
  const ForgetPwd({super.key, this.type = 1});

  @override
  State<ForgetPwd> createState() => _ForgetPwdState();
}

class _ForgetPwdState extends State<ForgetPwd> {


  String? password;
  String? surePassword;
  String? mail;
  String? code;
  bool isDisabled = true;
  bool isSureDisabled = true;

  Timer? _countdownTimer;
  int _countdownNum = 60;
  late String codeText;

  bool isDone = false;

  TextEditingController mailController = TextEditingController();
  TextEditingController codeController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  TextEditingController surePasswordController = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    codeText = get_code_btn.tr;
  }

  /// 获取验证码
  void getMsgCode() async {
    if(mail == null || mail!.isEmpty){
      showToast(mail_hintText.tr);
      return;
    }
    if(validateEmail(mail!) == false){
      showToast(email_input_error.tr);
      return;
    }
    if(_countdownNum != 60){
      return;
    }
    if (mail == null || mail!.isEmpty) {
      showToast(mail_hintText.tr);
      return;
    }
    showLoading();
    ResponseData res = await LoginAPI.sendPasswordEmail(mail!);
    hideLoading();
    if (res.code == 200) {
      startCountDownTimer();
    }
  }

  /// 开始倒计时
  startCountDownTimer() {
    if(_countdownTimer != null){
      _countdownTimer?.cancel();
      _countdownTimer = null;
      _countdownNum = 60;
      codeText = get_code_btn.tr;
    }
    _countdownTimer = Timer.periodic(new Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdownNum > 0) {
          codeText = "${_countdownNum--}s";
        } else {
          _countdownTimer?.cancel();
          _countdownTimer = null;
          _countdownNum = 60;
          codeText = get_code_btn.tr;
        }
      });
    });
  }

  getIsDone(){
    if(password == null || password!.isEmpty || surePassword == null || surePassword!.isEmpty || mail == null || mail!.isEmpty || code == null || code!.isEmpty){
      isDone = false;
    }else{
      isDone = true;
    }
    if(mounted){
      setState(() {});
    }
  }

  _register()async{
    if(mail==null || mail!.isEmpty){
      showToast(mail_hintText.tr);
      return;
    }
    if(validateEmail(mail!) == false){
      showToast(email_input_error.tr);
      return;
    }
    if(password!.length<6 || surePassword!.length < 6){
      showToast(pwd_length_less.tr);
      return;
    }
    if(password! != surePassword!){
      showToast(pwd_sure_pwd_error.tr);
      return;
    }
    Map<String,dynamic> data = {
      'email':mail,
      'password':password,
      'smscode':code,
      'confirmPassword':surePassword
    };
    showLoading();
    ResponseData res = await LoginAPI.forgetPassword(data);
    hideLoading();
    if(res.code == 200){
      showToast(forget_pwd_success.tr);
      LocalBaseInfo.setAccount(mail!);
      Navigator.of(context).pop();
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _countdownTimer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: defaultBlackBgColor,
      // appBar: myAppBar(context, ''),
      resizeToAvoidBottomInset: true,
      body: GestureDetector(
        onTap: (){
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Column(
          children: [
            Expanded(child: SingleChildScrollView(
              child: Container(
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(horizontal: 48.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    SizedBox(height:160.w,),
                    Container(
                      alignment: Alignment.centerLeft,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Visibility(child: GestureDetector(
                            onTap: (){
                              Navigator.of(context).pop();
                            },
                            child: Container(
                              child: Image.asset('assets/login/back.png',width: 56.w,),
                            ),
                          ),visible: true,),
                          SizedBox(height: 28.w,),
                          Container(
                            child: Text(widget.type== 1? 'Change your password'.tr:'Reset password'.tr,style: TextStyle(
                                color: Colors.white,
                                fontSize: 48.sp,
                                fontWeight: FontWeight.w600
                            ),maxLines: 1,overflow: TextOverflow.ellipsis,),
                          )
                        ],
                      ),
                    ),
                    SizedBox(height: 90.w,),
                    //邮箱
                    Container(
                      width: 750.w,
                      height: 108.w,
                      padding: EdgeInsets.symmetric(horizontal: 30.w),
                      decoration: BoxDecoration(
                          border: Border.all(color: Color.fromRGBO(255, 255, 255, 0.5),width: 1.w),
                          borderRadius: BorderRadius.circular(20.w)
                      ),
                      child:  Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Expanded(child: TextField(
                            //控制器
                            textInputAction: TextInputAction.done,
                            controller: mailController,
                            maxLines: 1,
                            //是否自动更正
                            autocorrect: true,
                            //是否自动对焦
                            autofocus: false,
                            style: inputStyle,
                            inputFormatters: [

                            ],
                            decoration: InputDecoration(
                              contentPadding: const EdgeInsets.symmetric(vertical: 0,horizontal: 0),
                              hintText: mail_hintText.tr,
                              hintStyle: inputHitStyle,
                              counterText: "",
                              border: OutlineInputBorder(
                                  borderSide: BorderSide.none),
                            ),
                            onChanged: (val){
                              setState(() {
                                mail = val.trim();
                              });
                              getIsDone();
                            },
                          )),
                          SizedBox(width: 20.w,),
                          Visibility(visible: mail!=null&&mail!.isNotEmpty,
                            child: GestureDetector(
                              onTap: (){
                                setState(() {
                                  mailController.text = '';
                                  mail = null;
                                });
                                getIsDone();
                              },
                              child: Container(
                                child: Image.asset('assets/common/input_close.png',width: 48.w,),
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                    SizedBox(height: 32.w,),
                    //验证码
                    Container(
                      width: 750.w,
                      height: 108.w,
                      child: Row(
                        children: [
                          Container(
                            width: 400.w,
                            height: 108.w,
                            padding: EdgeInsets.symmetric(horizontal: 30.w),
                            decoration: BoxDecoration(
                                border:inputBorder,
                                borderRadius: BorderRadius.circular(20.w)
                            ),
                            child:  Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Expanded(child: TextField(
                                  //控制器
                                  textInputAction: TextInputAction.done,
                                  controller: codeController,
                                  keyboardType: TextInputType.number,
                                  maxLines: 1,
                                  maxLength: 6,
                                  //是否自动更正
                                  autocorrect: true,
                                  //是否自动对焦
                                  autofocus: false,
                                  style: inputStyle,
                                  inputFormatters: [
                                    FilteringTextInputFormatter.allow(RegExp("[0-9]"))
                                  ],
                                  decoration: InputDecoration(
                                    contentPadding: const EdgeInsets.symmetric(vertical: 0,horizontal: 0),
                                    hintText: validate_code_hintText.tr,
                                    hintStyle: inputHitStyle,
                                    counterText: "",
                                    border: OutlineInputBorder(
                                        borderSide: BorderSide.none),
                                  ),
                                  onChanged: (val){
                                    setState(() {
                                      code = val.trim();
                                    });
                                    getIsDone();
                                  },
                                )),
                                SizedBox(width: 20.w,),
                                Visibility(visible: code!=null&&code!.isNotEmpty,
                                  child: GestureDetector(
                                    onTap: (){
                                      setState(() {
                                        codeController.text = '';
                                        code = '';
                                      });
                                      getIsDone();
                                    },
                                    child: Container(
                                      child: Image.asset('assets/common/input_close.png',width: 48.w,),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          SizedBox(width: 24.w,),
                          GestureDetector(
                            onTap: (){
                              getMsgCode();
                            },
                            child: Container(
                              width: 230.w,
                              height: 108.w,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  color: Color(0xff2B2B2B),
                                  borderRadius: BorderRadius.circular(16.w)
                              ),
                              child: Text(codeText,style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.w600,
                                  fontSize: 28.sp
                              ),),
                            ),
                          )
                        ],
                      ),
                    ),
                    SizedBox(height: 32.w,),
                    //密码
                    Container(
                      width: 750.w,
                      height: 108.w,
                      padding: EdgeInsets.symmetric(horizontal: 30.w),
                      decoration: BoxDecoration(
                          border: inputBorder,
                          borderRadius: BorderRadius.circular(20.w)
                      ),
                      child:  Row(
                        children: [
                          Expanded(child: TextField(
                            //控制器
                            controller: passwordController,
                            // maxLength: 11,
                            maxLines: 1,
                            //是否自动更正
                            autocorrect: true,
                            //是否自动对焦
                            autofocus: false,
                            obscureText: isDisabled, //是否是密码
                            style: inputStyle,
                            decoration:  InputDecoration(
                              //                hintText: "请输入用户名",
                              contentPadding: EdgeInsets.zero,
                              hintText: pwd_hintText.tr,
                              hintStyle: inputHitStyle,
                              counterText: "",
                              border: const OutlineInputBorder(
                                  borderSide: BorderSide.none),
                            ),
                            onChanged: (val) {
                              setState(() {
                                password = val.trim();
                              });
                              getIsDone();
                            },
                          )),
                          SizedBox(width: 20.w,),
                          GestureDetector(
                            onTap: (){
                              setState(() {
                                isDisabled = !isDisabled;
                              });
                            },
                            child: Container(
                              child: Image.asset(!isDisabled?'assets/common/input_show.png':'assets/common/input_hide.png',width: 56.w,),
                            ),
                          )
                        ],
                      ),
                    ),
                    SizedBox(height: 40.w,),
                    //确认密码
                    Container(
                      width: 750.w,
                      height: 108.w,
                      padding: EdgeInsets.symmetric(horizontal: 30.w),
                      decoration: BoxDecoration(
                          border: inputBorder,
                          borderRadius: BorderRadius.circular(20.w)
                      ),
                      child:  Row(
                        children: [
                          Expanded(child: TextField(
                            //控制器
                            controller: surePasswordController,
                            // maxLength: 11,
                            maxLines: 1,
                            //是否自动更正
                            autocorrect: true,
                            //是否自动对焦
                            autofocus: false,
                            obscureText: isSureDisabled, //是否是密码
                            style: inputStyle,
                            decoration:  InputDecoration(
                              //                hintText: "请输入用户名",
                              contentPadding: EdgeInsets.zero,
                              hintText: ensure_pwd_hintText.tr,
                              hintStyle: inputHitStyle,
                              counterText: "",
                              border: const OutlineInputBorder(
                                  borderSide: BorderSide.none),
                            ),
                            onChanged: (val) {
                              setState(() {
                                surePassword = val.trim();
                              });
                              getIsDone();
                            },
                          )),
                          SizedBox(width: 20.w,),
                          GestureDetector(
                            onTap: (){
                              setState(() {
                                isSureDisabled = !isSureDisabled;
                              });
                            },
                            child: Container(
                              child: Image.asset(!isSureDisabled?'assets/common/input_show.png':'assets/common/input_hide.png',width: 48.w,),
                            ),
                          )
                        ],
                      ),
                    ),
                    SizedBox(height: 500.h,),
                    GestureDetector(
                      onTap: () {
                        getIsDone();
                        if(isDone){
                          _register();
                        }
                      },
                      child: Container(
                        height: 108.w,
                        width: 750.w,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            color: isDone? themeColor:themeDisableColor,
                            borderRadius: BorderRadius.circular(8.w)
                        ),
                        child: Text(sure_btn.tr,style: TextStyle(
                            color: Colors.white,
                            fontSize: 28.sp,
                            fontWeight: FontWeight.w600
                        ),),
                      ),
                    ),
                  ],
                ),
              ),
            )),
            SizedBox(height: ScreenUtil().bottomBarHeight > 0?ScreenUtil().bottomBarHeight:48.w,),
          ],
        ),
      ),
    );
  }

}
